MailService.php
<?php
namespace Tlf\User;
use Tlf\User\Configurations as C;
/**
* Enum representing available mail (not male) services, for configuration purposes
*/
enum MailService: string {
case PHP_MAIL = 'php_mail';
case CUSTOM_CALLABLE = 'custom_callable';
case LIB_PHPMAILER = 'lib_phpmailer';
case DEBUG_TO_TEXTFILE = 'debug_to_textfile';
/**
* Bunch of configurations required. See README.
*/
static function send_phpmailer_mail(
array $phpmailer_configs,
string $to,
string $subject,
string $message,
array|string $additional_headers = [],
string $additional_params = ""
): bool {
//Create an instance; passing `true` enables exceptions
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = $phpmailer_configs[C::smtp_host]; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = $phpmailer_configs[C::email_from]; //SMTP username
$mail->Password = $phpmailer_configs[C::smtp_password]; //SMTP password
$mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom(
$phpmailer_configs[C::email_from],
$phpmailer_configs[C::name_from],
);
$mail->addAddress($to); //Name is optional
$mail->addReplyTo(
$phpmailer_configs[C::email_from]
);
// $mail->addCC('cc@example.com');
// $mail->addBCC('bcc@example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
ob_start();
$mail->send();
ob_get_clean();
error_log("Email sent with PHPMailer");
return true;
} catch (Exception $e) {
error_log("Email failed sending with PHPMailer. Error: {$mail->ErrorInfo}");
}
return false;
}
}